package org.adit.spring.hibernate.controller;

import java.io.FileNotFoundException;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

import org.adit.spring.hibernate.dao.FleetDao;
import org.adit.spring.hibernate.entity.Fleet;
import org.adit.spring.hibernate.entity.ResourceType;
import org.adit.spring.hibernate.entity.Route;
import org.adit.spring.hibernate.infra.Restrito;
import org.adit.spring.hibernate.parser.Caller;
import org.adit.spring.hibernate.parser.Parser;
import org.adit.spring.hibernate.parser.entity.FleetEngineInput;
import org.adit.spring.hibernate.parser.entity.FleetEngineOutput;
import org.adit.spring.hibernate.parser.entity.Job;
import org.tempuri.IRWFleetEngineProxy;

import br.com.caelum.vraptor.Delete;
import br.com.caelum.vraptor.Get;
import br.com.caelum.vraptor.Path;
import br.com.caelum.vraptor.Post;
import br.com.caelum.vraptor.Put;
import br.com.caelum.vraptor.Resource;
import br.com.caelum.vraptor.Result;
import br.com.caelum.vraptor.view.Results;

@Resource
public class FleetsController {

	private FleetDao dao;

	private final Result result;

	public FleetsController(FleetDao dao, Result result) {
		this.dao = dao;
		this.result = result;
	}

	@Restrito
	@Get
	@Path("/fleets/demo")
	public void demo() {

	}

	@Restrito
	@Post
	@Path("/fleets")
	public void adiciona(Fleet fleet) {

		dao.salva(fleet);
		result.redirectTo(FleetsController.class).lista();
	}

	@Get
	@Path("/fleetsx")
	public void enviaXML(String xml) {
		
		Caller caller = new Caller();
		
		try {
			caller.callerMeth();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
/*
		String testeDeSaida = "";
		// /System.out.println(route.getXml());
		try {
			FleetEngineOutput fleetEngineOutput = new FleetEngineOutput();
			IRWFleetEngineProxy fleetClient = new IRWFleetEngineProxy();
			String optimizeStartRespostaID = fleetClient
					.optimizeStart("<?xml version=\"1.0\" encoding=\"utf-8\"?><FleetEngineInput xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"	xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"	xsi:noNamespaceSchemaLocation=\"input.xsd\">	<Parameters>		<Matrix>StreetNetwork</Matrix>		<NumCapacities>1</NumCapacities>		<MaxCalculationTime>1</MaxCalculationTime>		<RandomSeed>1</RandomSeed>	</Parameters>	<Depots>		<Depot Id=\"D1\">			<X>-41.09270</X>			<Y>-20.89175</Y>		</Depot>	</Depots>	<ResourceTypes>		<ResourceType Id=\"Truck\">			<Cost>10000</Cost>			<CostKM>0</CostKM>			<CostDriveTime>1</CostDriveTime>			<CostWaitTime>1</CostWaitTime>			<CostServiceTime>0</CostServiceTime>			<Capacities>				<Capacity Ind=\"1\">18060</Capacity>			</Capacities>			<Network>13</Network>		</ResourceType>	</ResourceTypes>	<Resources>		<Resource Id=\"Truck1\">			<ResourceType>Truck</ResourceType>			<ResourcePeriods>				<ResourcePeriod Id=\"RP1\">					<StartDepot>D1</StartDepot>					<StopDepot>D1</StopDepot>					<Start>2010-01-01T08:00:00</Start>					<Stop>2010-12-31T17:59:59</Stop>				</ResourcePeriod>			</ResourcePeriods>		</Resource>			</Resources>	<Jobs>		<Job Id=\"J1\">    		<Demands>   			<Demand Ind=\"1\">1</Demand>		</Demands>			<Pickup>				<X>-46.6486284837213</X>				<Y>-23.56715284992</Y>			</Pickup>		</Job>		<Job Id=\"J2\">    		<Demands>   			<Demand Ind=\"1\">1</Demand>		</Demands>			<Pickup>				<X>-46.6486284837213</X>				<Y>-23.56715284992</Y>			</Pickup>		</Job>		<Job Id=\"J3\">    		<Demands>   			<Demand Ind=\"1\">1</Demand>		</Demands>			<Pickup>				<X>-46.6486284837213</X>				<Y>-23.56715284992</Y>			</Pickup>		</Job>		<Job Id=\"J4\">    		<Demands>   			<Demand Ind=\"1\">1</Demand>		</Demands>			<Pickup>				<X>-46.5185858889901</X>				<Y>-23.5832345050174</Y>			</Pickup>		</Job>	</Jobs></FleetEngineInput>");

			String getResultTemp = "";

			if (!optimizeStartRespostaID.equals("")) {
				getResultTemp = fleetClient.getResult(optimizeStartRespostaID);
			}
			System.out.println(getResultTemp);
			fleetEngineOutput = buscaXmlOutput(getResultTemp);
			for (Job job : fleetEngineOutput.getJobs()) {
				System.out.println(job.getResource());
				testeDeSaida.concat(job.getResource() + "<BR/>");
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}*/
	}

	@Post
	@Path("/fleets/xml")
	public Route testeXML(Route route) {
		Route retRoute = new Route();
		String testeDeSaida = "";
		System.out.println(route.getXml());
		try {
			FleetEngineOutput fleetEngineOutput = new FleetEngineOutput();
			IRWFleetEngineProxy fleetClient = new IRWFleetEngineProxy();
			String optimizeStartResposta = fleetClient.optimizeStart(route.getXml());
			String getResultTemp = "";

			if (!optimizeStartResposta.equals("")) {
				getResultTemp = fleetClient.getResult(optimizeStartResposta);
			}
			System.out.println(getResultTemp);
			fleetEngineOutput = buscaXmlOutput(getResultTemp);

			// Aqui vc transfere um objeto da regra de nogocio -> parser para um objeto de tela que pode ser acessado no JSP
			route.setDescricao(fleetEngineOutput.getResult().getDist());

			for (Job job : fleetEngineOutput.getJobs()) {
				System.out.println(job.getResource());
				testeDeSaida.concat(job.getResource() + "<BR/>");
			}

		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (RemoteException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return route;
	}

	@Restrito
	@Get
	@Path("/fleets/novo")
	public void formulario() {

	}

	@Restrito
	@Get
	@Path("/fleets/{id}")
	public Fleet edita(Long id) {
		return dao.carrega(id);
	}

	@Restrito
	@Put
	@Path("/fleets/{fleet.id}")
	public void altera(Fleet fleet) {
		dao.atualiza(fleet);
		result.redirectTo(FleetsController.class).lista();
	}

	@Restrito
	@Delete
	@Path("/fleets/{id}")
	public void remove(Long id) {
		Fleet fleet = dao.carrega(id);
		dao.remove(fleet);
		result.redirectTo(FleetsController.class).lista();
	}

	@Get
	@Path("/fleets/busca")
	public List<Fleet> lista() {
		List<Fleet> fleetList = new ArrayList<Fleet>();

		try {
			FleetEngineInput fleetEngineInput = new FleetEngineInput();
			fleetEngineInput = buscaXmlInput("fleet");
			for (Job job : fleetEngineInput.getJobs()) {
				System.out.println(job.getId());
			}

			for (org.adit.spring.hibernate.parser.entity.Resource resource : fleetEngineInput.getResources()) {
				Fleet fleet = new Fleet();
				fleet.setType(resource.getResourcetype());
				fleet.setDescricao(resource.getId());

				for (org.adit.spring.hibernate.parser.entity.ResourcePeriod resourcePeriod : resource.getResourceperiods()) {
					fleet.setStart(resourcePeriod.getStart());
					fleet.setStop(resourcePeriod.getStop());
					fleetList.add(fleet);
				}

			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return fleetList;
	}

	@Get
	@Path("/fleets")
	public Fleet busca() {
		Fleet fleet = new Fleet();

		try {
			FleetEngineInput fleetEngineInput = new FleetEngineInput();
			fleetEngineInput = buscaXmlInput("fleet");
			for (Job job : fleetEngineInput.getJobs()) {
				System.out.println(job.getResource());
			}

			for (org.adit.spring.hibernate.parser.entity.Resource resource : fleetEngineInput.getResources()) {
				fleet.setType(resource.getResourcetype());
				for (org.adit.spring.hibernate.parser.entity.ResourcePeriod resourcePeriod : resource.getResourceperiods()) {
					fleet.setStart(resourcePeriod.getStart());
					fleet.setStop(resourcePeriod.getStop());
				}

			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
		return fleet;
	}

	private ResourceType setResourceTypeAttributes(String resourcetype, String resourcetype2) {
		// TODO Auto-generated method stub
		return null;
	}

	public FleetEngineOutput buscaXmlOutput(String xmlIdentifier) throws FileNotFoundException {
		Parser parser = new Parser();
		return parser.getXmlOutput(xmlIdentifier);
	}

	public FleetEngineInput buscaXmlInput(String xmlIdentifier) throws FileNotFoundException {
		Parser parser = new Parser();
		return parser.getXmlInput(xmlIdentifier);
	}

	public List<Fleet> busca(String nome) {
		result.include("nome", nome);
		return dao.busca(nome);
	}

	@Get
	@Path("/fleets/busca.json")
	public void buscaJson(String q) {
		result.use(Results.json()).from(dao.busca(q)).exclude("id", "descricao").serialize();
	}
}